<template>
  <div class="app-container">
    <el-container>
      <el-main>
        <!-- 搜索和操作栏 -->
        <div class="top">
          <el-row>
            <el-col :span="16">
              <el-input
                v-model="listQuery.kw"
                placeholder="搜索会话名称、手机号、服务器IP"
                style="width: 350px"
                @keyup.enter.native="searchSessions"
              >
                <el-button slot="append" icon="el-icon-search" @click="searchSessions" />
              </el-input>
              <el-select v-model="listQuery.status" placeholder="会话状态" clearable style="margin-left: 10px; width: 120px;">
                <el-option label="在线" value="online" />
                <el-option label="离线" value="offline" />
                <el-option label="连接中" value="connecting" />
                <el-option label="错误" value="error" />
              </el-select>
              <el-input
                v-model="listQuery.server_ip"
                placeholder="服务器IP"
                style="width: 150px; margin-left: 10px"
                clearable
              />
            </el-col>
            <el-col :span="8" class="text-right">
              <el-button
                v-if="hasUserPermission"
                class="add-btn"
                type="primary"
                @click="showSessionDialog"
              >
                新建会话
              </el-button>
              <el-dropdown style="margin-left: 10px;" @command="handleBatchCommand">
                <el-button type="success">
                  批量操作<i class="el-icon-arrow-down el-icon--right" />
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="start">批量启动</el-dropdown-item>
                  <el-dropdown-item command="stop">批量停止</el-dropdown-item>
                  <el-dropdown-item command="sync">同步状态</el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </el-col>
          </el-row>
        </div>

        <!-- 会话列表 -->
        <el-table
          v-loading="listLoading"
          :data="sessionList"
          border
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="session_name" label="会话名称" min-width="120">
            <template slot-scope="scope">
              <el-link type="primary" @click="viewSessionDetail(scope.row)">
                {{ scope.row.session_name }}
              </el-link>
            </template>
          </el-table-column>
          <el-table-column prop="phone" label="手机号" width="120" />
          <el-table-column prop="server_ip" label="服务器IP" width="120" />
          <el-table-column prop="server_port" label="端口" width="80" />
          <el-table-column prop="waha_api_url" label="API地址" min-width="150" show-overflow-tooltip>
            <template slot-scope="scope">
              <span v-if="scope.row.waha_api_url">{{ scope.row.waha_api_url }}</span>
              <span v-else class="text-muted">未配置</span>
            </template>
          </el-table-column>
          <el-table-column prop="waha_api_key" label="API密钥" width="120">
            <template slot-scope="scope">
              <span v-if="scope.row.waha_api_key">
                <el-tag type="success" size="mini">已配置</el-tag>
              </span>
              <span v-else class="text-muted">未配置</span>
            </template>
          </el-table-column>
          <el-table-column prop="session_status" label="状态" width="100">
            <template slot-scope="scope">
              <el-tag
                :type="scope.row.session_status === 'online' ? 'success' :
                  scope.row.session_status === 'connecting' ? 'warning' :
                  scope.row.session_status === 'error' ? 'danger' : 'info'"
              >
                {{ getStatusText(scope.row.session_status) }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="note" label="备注" min-width="100" show-overflow-tooltip />
          <el-table-column prop="create_at" label="创建时间" width="150">
            <template slot-scope="scope">
              {{ formatDate(scope.row.create_at) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="280" fixed="right">
            <template slot-scope="scope">
              <el-button
                size="mini"
                :type="scope.row.session_status === 'offline' ? 'success' : 'warning'"
                :loading="scope.row.statusLoading"
                @click="toggleSessionStatus(scope.row)"
              >
                {{ scope.row.session_status === 'offline' ? '启动' : '停止' }}
              </el-button>
              <el-button
                size="mini"
                :loading="scope.row.syncLoading"
                @click="syncSessionStatus(scope.row)"
              >
                同步状态
              </el-button>
              <el-button
                v-if="hasUserPermission"
                size="mini"
                @click="editSession(scope.row)"
              >
                编辑
              </el-button>
              <el-button
                v-if="hasUserPermission"
                size="mini"
                type="danger"
                @click="deleteSession(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
          v-show="total > 0"
          background
          :current-page="listQuery.page"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="listQuery.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          class="mt-pagination"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </el-main>
    </el-container>

    <!-- 新建/编辑会话对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="600px"
      @close="resetForm"
    >
      <el-form
        ref="sessionForm"
        :model="sessionForm"
        :rules="sessionRules"
        label-width="100px"
      >
        <el-form-item label="会话名称" prop="session_name">
          <el-input v-model="sessionForm.session_name" placeholder="请输入会话名称" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="sessionForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="服务器IP" prop="server_ip">
          <el-input v-model="sessionForm.server_ip" placeholder="请输入服务器IP地址" />
        </el-form-item>
        <el-form-item label="服务器端口" prop="server_port">
          <el-input-number v-model="sessionForm.server_port" :min="1" :max="65535" placeholder="8000" />
        </el-form-item>
        <el-form-item label="API地址" prop="waha_api_url">
          <el-input v-model="sessionForm.waha_api_url" placeholder="请输入WAHA API访问地址，如：http://127.0.0.1:3000" />
        </el-form-item>
        <el-form-item label="API密钥" prop="waha_api_key">
          <el-input v-model="sessionForm.waha_api_key" placeholder="请输入WAHA API密钥" show-password />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="sessionForm.note"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getWahaSessionList,
  createWahaSession,
  updateWahaSession,
  deleteWahaSession,
  startWahaSession,
  stopWahaSession,
  syncWahaSessionStatus,
  batchStartWahaSessions,
  batchStopWahaSessions
} from '@/api/chatbot/waha-session'

export default {
  name: 'WahaSession',
  data() {
    return {
      // 列表相关
      sessionList: [],
      listLoading: false,
      total: 0,
      listQuery: {
        page: 1,
        pageSize: 20,
        kw: '',
        status: '',
        server_ip: ''
      },
      selectedSessions: [],

      // 对话框相关
      dialogVisible: false,
      dialogTitle: '新建会话',
      submitLoading: false,
      isEdit: false,
      currentSessionId: null,

      // 表单相关
      sessionForm: {
        session_name: '',
        phone: '',
        server_ip: '',
        server_port: 8000,
        waha_api_url: '',
        waha_api_key: '',
        note: ''
      },
      sessionRules: {
        session_name: [
          { required: true, message: '请输入会话名称', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' }
        ],
        server_ip: [
          { required: true, message: '请输入服务器IP', trigger: 'blur' }
        ],
        server_port: [
          { required: true, message: '请输入服务器端口', trigger: 'blur' }
        ],
        waha_api_url: [
          { required: true, message: '请输入WAHA API访问地址', trigger: 'blur' }
        ],
        waha_api_key: [
          { required: true, message: '请输入WAHA API密钥', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    hasUserPermission() {
      return this.$store.getters.roles.indexOf('chatbot_user') !== -1 ||
             this.$store.getters.roles.indexOf('admin') !== -1
    }
  },
  created() {
    this.fetchSessionList()
  },
  methods: {
    // 获取会话列表
    fetchSessionList() {
      this.listLoading = true
      const params = new URLSearchParams()
      params.append('page', this.listQuery.page)
      params.append('pagesize', this.listQuery.pageSize)
      if (this.listQuery.kw) params.append('kw', this.listQuery.kw)
      if (this.listQuery.status) params.append('status', this.listQuery.status)
      if (this.listQuery.server_ip) params.append('server_ip', this.listQuery.server_ip)

      getWahaSessionList(params.toString())
        .then(response => {
          if (response.success) {
            this.sessionList = response.data.data.map(item => ({
              ...item,
              statusLoading: false,
              syncLoading: false
            }))
            this.total = response.data.total
          } else {
            this.$message.error(response.msg || '获取会话列表失败')
          }
        })
        .catch(error => {
          console.error('获取会话列表失败:', error)
          this.$message.error('获取会话列表失败')
        })
        .finally(() => {
          this.listLoading = false
        })
    },

    // 搜索会话
    searchSessions() {
      this.listQuery.page = 1
      this.fetchSessionList()
    },

    // 分页处理
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.fetchSessionList()
    },

    handlePageChange(val) {
      this.listQuery.page = val
      this.fetchSessionList()
    },

    // 选择行处理
    handleSelectionChange(selection) {
      this.selectedSessions = selection
    },

    // 批量操作
    handleBatchCommand(command) {
      if (this.selectedSessions.length === 0) {
        this.$message.warning('请先选择要操作的会话')
        return
      }

      const ids = this.selectedSessions.map(item => item.id)
      const sessionNames = this.selectedSessions.map(item => item.session_name).join('、')

      if (command === 'start') {
        this.$confirm(`确定要启动选中的 ${ids.length} 个会话吗？\n${sessionNames}`, '批量启动', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          batchStartWahaSessions(ids)
            .then(response => {
              if (response.success) {
                this.$message.success('批量启动成功')
                this.fetchSessionList()
              } else {
                this.$message.error(response.msg || '批量启动失败')
              }
            })
            .catch(error => {
              console.error('批量启动失败:', error)
              this.$message.error('批量启动失败')
            })
        })
      } else if (command === 'stop') {
        this.$confirm(`确定要停止选中的 ${ids.length} 个会话吗？\n${sessionNames}`, '批量停止', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          batchStopWahaSessions(ids)
            .then(response => {
              if (response.data.success) {
                this.$message.success('批量停止成功')
                this.fetchSessionList()
              } else {
                this.$message.error(response.data.msg || '批量停止失败')
              }
            })
            .catch(error => {
              console.error('批量停止失败:', error)
              this.$message.error('批量停止失败')
            })
        })
      } else if (command === 'sync') {
        this.$message.info('正在同步状态...')
        Promise.all(ids.map(id => syncWahaSessionStatus(id)))
          .then(() => {
            this.$message.success('批量同步状态完成')
            this.fetchSessionList()
          })
          .catch(error => {
            console.error('批量同步状态失败:', error)
            this.$message.error('批量同步状态失败')
          })
      }
    },

    // 切换会话状态
    toggleSessionStatus(session) {
      this.$set(session, 'statusLoading', true)

      const action = session.session_status === 'offline' ? startWahaSession : stopWahaSession
      const actionText = session.session_status === 'offline' ? '启动' : '停止'

      action(session.id)
        .then(response => {
          if (response.success) {
            this.$message.success(`${actionText}会话成功`)
            this.fetchSessionList()
          } else {
            this.$message.error(response.msg || `${actionText}会话失败`)
          }
        })
        .catch(error => {
          console.error(`${actionText}会话失败:`, error)
          this.$message.error(`${actionText}会话失败`)
        })
        .finally(() => {
          this.$set(session, 'statusLoading', false)
        })
    },

    // 同步会话状态
    syncSessionStatus(session) {
      this.$set(session, 'syncLoading', true)

      syncWahaSessionStatus(session.id)
        .then(response => {
          if (response.success) {
            this.$message.success('同步状态成功')
            this.fetchSessionList()
          } else {
            this.$message.error(response.msg || '同步状态失败')
          }
        })
        .catch(error => {
          console.error('同步状态失败:', error)
          this.$message.error('同步状态失败')
        })
        .finally(() => {
          this.$set(session, 'syncLoading', false)
        })
    },

    // 显示会话对话框
    showSessionDialog() {
      this.dialogTitle = '新建会话'
      this.isEdit = false
      this.currentSessionId = null
      this.dialogVisible = true
    },

    // 编辑会话
    editSession(session) {
      this.dialogTitle = '编辑会话'
      this.isEdit = true
      this.currentSessionId = session.id
      this.sessionForm = {
        session_name: session.session_name,
        phone: session.phone,
        server_ip: session.server_ip,
        server_port: session.server_port,
        waha_api_url: session.waha_api_url || '',
        waha_api_key: session.waha_api_key || '',
        note: session.note || ''
      }
      this.dialogVisible = true
    },

    // 查看会话详情
    viewSessionDetail(session) {
      this.$message.info(`查看会话详情: ${session.session_name}`)
      // 这里可以实现查看详情的逻辑
    },

    // 删除会话
    deleteSession(session) {
      this.$confirm(`确定要删除会话 "${session.session_name}" 吗？此操作不可恢复！`, '删除会话', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteWahaSession(session.id)
          .then(response => {
            if (response.success) {
              this.$message.success('删除会话成功')
              this.fetchSessionList()
            } else {
              this.$message.error(response.msg || '删除会话失败')
            }
          })
          .catch(error => {
            console.error('删除会话失败:', error)
            this.$message.error('删除会话失败')
          })
      })
    },

    // 提交表单
    submitForm() {
      this.$refs.sessionForm.validate((valid) => {
        if (valid) {
          this.submitLoading = true

          const action = this.isEdit
            ? updateWahaSession(this.currentSessionId, this.sessionForm)
            : createWahaSession(this.sessionForm)

          action
            .then(response => {
              if (response.success) {
                this.$message.success(this.isEdit ? '更新会话成功' : '创建会话成功')
                this.dialogVisible = false
                this.fetchSessionList()
              } else {
                this.$message.error(response.msg || (this.isEdit ? '更新会话失败' : '创建会话失败'))
              }
            })
            .catch(error => {
              console.error(this.isEdit ? '更新会话失败:' : '创建会话失败:', error)
              this.$message.error(this.isEdit ? '更新会话失败' : '创建会话失败')
            })
            .finally(() => {
              this.submitLoading = false
            })
        }
      })
    },

    // 重置表单
    resetForm() {
      this.sessionForm = {
        session_name: '',
        phone: '',
        server_ip: '',
        server_port: 8000,
        waha_api_url: '',
        waha_api_key: '',
        note: ''
      }
      if (this.$refs.sessionForm) {
        this.$refs.sessionForm.resetFields()
      }
    },

    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        'online': '在线',
        'offline': '离线',
        'connecting': '连接中',
        'error': '错误'
      }
      return statusMap[status] || status
    },

    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '-'
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN')
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.top {
  margin-bottom: 20px;
}

.add-btn {
  float: right;
}

.text-right {
  text-align: right;
}

.mt-pagination {
  margin-top: 20px;
  text-align: center;
}

.dialog-footer {
  text-align: right;
}

.text-muted {
  color: #999;
  font-style: italic;
}
</style>
